class Solution {
public:
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };
    int orangesRotting(vector<vector<int>>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        int min = 0;
        int fresh = 0;
        //
        queue<pair<int, int>> rot;
        //
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 2)
                    rot.push({ i, j });
                if (grid[i][j] == 1)
                    fresh++;
            }
        }
        //

        while (!rot.empty() && fresh > 0) {
            int size = rot.size();
            for (int i = 0; i < size; i++) {
                for (int k = 0; k < 4; k++) {
                    int x = rot.front().first + dx[k];
                    int y = rot.front().second + dy[k];

                    if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) {
                        fresh--;
                        grid[x][y] = 2;
                        rot.push({ x, y });
                    }
                }
                rot.pop();
            }
            min++;
        }

        if (fresh == 0) return min;
        else return -1;
    }
};